﻿using Bigway.Common.Models.DbModels;

namespace Bigway.Common.Services.Repositories;

public class SoftwareSystemRepository(IServiceProvider sp) :
    BaseSqliteRepository<SoftwareSystem>(sp),
    ISoftwareSystemRepository
{
    public async Task<SoftwareSystem?> GetAsync(string systemId, CancellationToken token = default)
    {
        return await Queryable.FirstAsync(x => x.Id == systemId, token);
    }

    public async Task InitializeAllAsync(CancellationToken token = default)
    {
        var systems = new List<SoftwareSystem>
        {
            new SoftwareSystem
            {
                Id = SystemIds.GiftPiker,
                Name = "派颂乐",
                Description = "一个基于商圈的权益卡活动, 礼物派送系统"
            }
        };
        var existingSystems = await GetAllAsync(token);
        var existingSystemsMap = existingSystems.ToDictionary(x => x.Id);
        var newSystems = systems
            .Where(x => !existingSystemsMap.ContainsKey(x.Id))
            .ToList();
        if (newSystems.Count > 0)
            await AddAllAsync(newSystems, token);

        var updatedSystems = systems
            .Where(x => existingSystemsMap.TryGetValue(x.Id, out var system) &&
                        (x.Name != system.Name || x.Description != system.Description))
            .ToList();
        if (updatedSystems.Count > 0)
            await UpdateAllAsync(updatedSystems, token);
    }
}